<template>
	<div class="table-config-container layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<div class="table-config-search mb15">
				<el-input v-model="state.tableData.param.query" size="default" placeholder="请输入配置名称" style="max-width: 180px"></el-input>
				<el-button size="default" type="primary" class="ml10" @click="getTableData">
					<el-icon>
						<ele-Search />
					</el-icon>
					查询
				</el-button>
				<el-button size="default" type="success" class="ml10" @click="onOpenAddConfig('add')">
					<el-icon>
						<ele-FolderAdd />
					</el-icon>
					新增配置
				</el-button>
			</div>
			<el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%">
				<el-table-column type="index" label="序号" width="100" />
				<el-table-column prop="name" label="配置名称" show-overflow-tooltip></el-table-column>
				<el-table-column prop="description" label="配置描述" show-overflow-tooltip></el-table-column>
				<el-table-column prop="fieldCount" label="字段数量" width="120">
					<template #default="scope">
						{{ scope.row.fields ? scope.row.fields.length : 0 }}
					</template>
				</el-table-column>
				<el-table-column label="表格字段数" width="100">
					<template #default="scope">
						{{ scope.row.tableFields ? scope.row.tableFields.length : 0 }}
					</template>
				</el-table-column>
				<el-table-column label="数据权限" width="100">
					<template #default="scope">
						<el-tag :type="scope.row.dataPermission ? 'success' : 'info'" size="small">
							{{ scope.row.dataPermission ? '启用' : '禁用' }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="创建时间" show-overflow-tooltip></el-table-column>
				<el-table-column label="操作" width="300">
					<template #default="scope">
						<el-button size="small" text type="primary" @click="onOpenEditConfig('edit', scope.row)">修改</el-button>
						<el-button size="small" text type="success" @click="onPreviewConfig(scope.row)">预览</el-button>
						<el-button size="small" text type="info" @click="onViewTable(scope.row)">查看表格</el-button>
						<el-button size="small" text type="danger" @click="onRowDel(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange"
				class="mt15"
				:pager-count="5"
				:page-sizes="[10, 20, 30]"
				v-model:current-page="state.tableData.param.page"
			background
			v-model:page-size="state.tableData.param.size"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.tableData.total"
			>
			</el-pagination>
		</el-card>

		<!-- 配置设计对话框 -->
		<el-dialog
			v-model="state.configDialog.isShowDialog"
			:title="state.configDialog.title"
			width="90%"
			top="5vh"
			:before-close="onCloseConfigDialog"
		>
			<TableFormDesigner
				v-model="state.configForm.fields"
				:config-name="state.configForm.name"
				@save="onSaveConfig"
			/>
		</el-dialog>

		<!-- 预览对话框 -->
		<el-dialog
			v-model="state.previewDialog.isShowDialog"
			title="配置预览"
			width="800px"
		>
			<div class="preview-content">
				<h4>表单字段预览</h4>
				<el-form label-width="120px">
					<el-form-item
						v-for="field in state.previewConfig.fields"
						:key="field.id"
						:label="field.label"
						:required="field.required"
					>
						<component
							:is="getFieldComponent(field.type)"
							v-bind="getFieldProps(field)"
							:placeholder="field.placeholder"
							disabled
						/>
					</el-form-item>
				</el-form>

				<h4>表格字段预览</h4>
				<el-table :data="[]" style="width: 100%">
					<el-table-column type="index" label="序号" width="60" />
					<el-table-column
						v-for="field in state.previewConfig.tableFields"
						:key="field.id"
						:prop="field.name"
						:label="field.label"
						:width="field.tableWidth"
						show-overflow-tooltip
					></el-table-column>
					<el-table-column label="操作" width="200">
						<template #default>
							<el-button size="small" text type="primary">修改</el-button>
							<el-button size="small" text type="danger">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="tableConfig">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { tableConfigApi } from '/@/api/tableConfig';
import { FieldType } from '/@/components/FormDesigner/types';

// 引入组件
const TableFormDesigner = defineAsyncComponent(() => import('./TableFormDesigner.vue'));

const router = useRouter();

// 定义变量内容
const state = reactive({
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			query: '',
			page: 1,
			size: 10,
		},
	},
	configDialog: {
		isShowDialog: false,
		type: '',
		title: '',
	},
	configForm: {
		id: undefined,
		name: '',
		description: '',
		dataPermission: false,
		fields: [],
		tableFields: [],
	},
	previewDialog: {
		isShowDialog: false,
	},
	previewConfig: {
		fields: [],
		tableFields: [],
	},
});

// 初始化表格数据
const getTableData = () => {
	state.tableData.loading = true;
	tableConfigApi()
		.getConfigList(state.tableData.param)
		.then((res) => {
			if (res.code === 0) {
				state.tableData.data = res.data.records;
				state.tableData.total = res.data.total;
			} else {
				ElMessage.error(res.msg || '获取数据失败');
			}
			setTimeout(() => {
				state.tableData.loading = false;
			}, 500);
		})
		.catch((err) => {
			state.tableData.loading = false;
			ElMessage.error(err.msg || '请求失败');
		});
};

// 打开新增配置弹窗
const onOpenAddConfig = (type: string) => {
	state.configDialog.type = type;
	state.configDialog.title = '新增表格配置';
	state.configForm = {
		id: undefined,
		name: '',
		description: '',
		dataPermission: false,
		fields: [],
		tableFields: [],
	};
	state.configDialog.isShowDialog = true;
};

// 打开修改配置弹窗
const onOpenEditConfig = (type: string, row: any) => {
	state.configDialog.type = type;
	state.configDialog.title = '修改表格配置';
	
	// 确保fields是数组格式
	let fields = [];
	if (row.fields) {
		if (Array.isArray(row.fields)) {
			fields = row.fields;
		} else if (typeof row.fields === 'string') {
			try {
				fields = JSON.parse(row.fields);
				if (!Array.isArray(fields)) {
					fields = [];
				}
			} catch (e) {
				fields = [];
			}
		}
	}
	
	state.configForm = {
		id: row.id,
		name: row.name,
		description: row.description,
		dataPermission: row.dataPermission || false,
		fields: fields,
		tableFields: row.tableFields || [],
	};
	state.configDialog.isShowDialog = true;
};

// 关闭配置对话框
const onCloseConfigDialog = () => {
	state.configDialog.isShowDialog = false;
};

// 保存配置
const onSaveConfig = (config: any) => {
	const saveData = {
		...state.configForm,
		...config,
	};

	const apiMethod = state.configDialog.type === 'add' ? 'saveConfig' : 'updateConfig';

	tableConfigApi()[apiMethod](saveData)
		.then((res) => {
			if (res.code === 0) {
				getTableData();
				state.configDialog.isShowDialog = false;
				ElMessage.success('操作成功');
			} else {
				ElMessage.error(res.msg || '操作失败');
			}
		})
		.catch((err) => {
			ElMessage.error(err.msg || '请求失败');
		});
};

// 预览配置
const onPreviewConfig = (row: any) => {
	// 确保fields是数组格式
	let fields = [];
	if (row.fields) {
		if (Array.isArray(row.fields)) {
			fields = row.fields;
		} else if (typeof row.fields === 'string') {
			try {
				fields = JSON.parse(row.fields);
				if (!Array.isArray(fields)) {
					fields = [];
				}
			} catch (e) {
				fields = [];
			}
		}
	}
	
	state.previewConfig = {
		fields: fields,
		tableFields: fields.filter((field: any) => field.showInTable),
	};
	state.previewDialog.isShowDialog = true;
};

// 查看表格
const onViewTable = (row: any) => {
	router.push({
		path: `/dynamic-table/${row.name}`,
	});
};

// 删除配置
const onRowDel = (row: any) => {
	ElMessageBox.confirm(`此操作将永久删除配置"${row.name}"，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			tableConfigApi()
				.deleteConfig({ id: row.id })
				.then((res) => {
					if (res.code === 0) {
						getTableData();
						ElMessage.success('删除成功');
					} else {
						ElMessage.error(res.msg || '删除失败');
					}
				})
				.catch((err) => {
					ElMessage.error(err.msg || '删除失败');
				});
		})
		.catch(() => {});
};

// 分页改变
const onHandleSizeChange = (val: number) => {
	state.tableData.param.size = val;
	getTableData();
};

// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.tableData.param.page = val;
	getTableData();
};

// 获取字段组件
const getFieldComponent = (type: FieldType) => {
	const componentMap = {
		[FieldType.TEXT]: 'el-input',
		[FieldType.TEXTAREA]: 'el-input',
		[FieldType.NUMBER]: 'el-input-number',
		[FieldType.SELECT]: 'el-select',
		[FieldType.RADIO]: 'el-radio-group',
		[FieldType.CHECKBOX]: 'el-checkbox-group',
		[FieldType.DATE]: 'el-date-picker',
		[FieldType.DATETIME]: 'el-date-picker',
		[FieldType.FILE]: 'el-upload',
	};
	return componentMap[type] || 'el-input';
};

// 获取字段属性
const getFieldProps = (field: any) => {
	const baseProps: Record<string, any> = {};

	switch (field.type) {
		case FieldType.TEXTAREA:
			baseProps.type = 'textarea';
			break;
		case FieldType.DATE:
			baseProps.type = 'date';
			break;
		case FieldType.DATETIME:
			baseProps.type = 'datetime';
			break;
	}

	return baseProps;
};

// 页面加载时
onMounted(() => {
	getTableData();
});
</script>

<style scoped>
.table-config-container {
	height: 100%;
}

.preview-content {
	max-height: 600px;
	overflow-y: auto;
}

.preview-content h4 {
	margin: 20px 0 10px 0;
	color: #409eff;
	border-bottom: 1px solid #e4e7ed;
	padding-bottom: 8px;
}

.preview-content h4:first-child {
	margin-top: 0;
}
</style>